package com.lovestudying.controller;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;

import com.google.gson.Gson;
import com.lovestudying.entity.Account;
import com.lovestudying.entity.Order;
import com.lovestudying.service.AccountService;
import com.lovestudying.service.OrderService;
import com.lovestudying.service.impl.AccountServiceImpl;
import com.lovestudying.service.impl.OrderServiceImpl;
import com.lovestudying.util.DBUtil_Pro;
import com.lovestudying.util.PageInfo;

/**
 * Servlet implementation class AccountPersonalCenterServlet
 */
/**
 * @author 子玉
 *
 */
@WebServlet("/AccountPersonalCenterServlet")
@MultipartConfig
public class AccountPersonalCenterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	// 调用业务层AccountService-AccountServiceImpl
	private AccountService accountService = new AccountServiceImpl();

	// 调用业务层OrderService-OrderServiceImpl
	private OrderService orderService = new OrderServiceImpl();

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AccountPersonalCenterServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 获取op属性值（前端jsp页面、ajax异步请求传进来的值）
		String op = request.getParameter("op");

		// 进行判断
		if ("personalCenter".equals(op)) {
			// 显示个人中心的信息
			accountCenter(request, response);

		} else if ("orderView".equals(op)) {
			// 显示订单信息
			orderView(request, response);

		} else if ("deleteOrder".equals(op)) {
			// 取消订单
			deleteOrder(request, response);
		}
	}

	private void deleteOrder(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 获取订单Id
		String orderId = request.getParameter("orderId");

		// 创建两个集合
		Map<String, Object> Set_Param = new HashMap<>();
		Set_Param.put("order_state", 3);
		Map<String, Object> Where_Param = new HashMap<>();
		Where_Param.put("order_id", orderId);

		// 调用业务层
		orderService.UpdateOrderByOrderId(Set_Param, Where_Param);

		// 显示订单信息
		orderView(request, response);

	}

	private void viewUpdate(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		Integer x = new Double(Double.parseDouble(request.getParameter("pic-x"))).intValue();
		Integer y = new Double(Double.parseDouble(request.getParameter("pic-y"))).intValue();
		Integer destWidth = new Double(Double.parseDouble(request.getParameter("destWidth"))).intValue();
		Integer destHeight = new Double(Double.parseDouble(request.getParameter("destHeight"))).intValue();
		Integer finalWidth = new Double(Double.parseDouble(request.getParameter("finalWidth"))).intValue();
		Integer finalHeight = new Double(Double.parseDouble(request.getParameter("finalHeight"))).intValue();

		// 接受普通组件
		String accountId = request.getParameter("accountId");
		String accountName = request.getParameter("accountName");
		String accountPhone = request.getParameter("accountPhone");
		String accountEmail = request.getParameter("accountEmail");
		String accountPsw = request.getParameter("accountPsw");

		// 判断是否修改密码
		if ("".equals(accountPsw)) {
			// 接受文件组件
			Part part = request.getPart("facePicture");

			// 允许的文件图片类型
			String allowImgType = "image/jpg,image/jpeg,image/png";
			// 允许的文件图片类型集合
			List<String> allowImgTypeList = Arrays.asList(allowImgType.split(","));

			// 判断上传的文件类型是否合法
			String contentType = part.getContentType(); // 获取上传文件的MIME类型
			if (allowImgTypeList.contains(contentType) == false) {
				// 创建集合
				Map<String, Object> Set_Param = new HashMap<String, Object>();
				Set_Param.put("account_name", accountName);
				Set_Param.put("account_phone", accountPhone);
				Set_Param.put("account_email", accountEmail);

				Map<String, Object> Where_Param = new HashMap<String, Object>();
				Where_Param.put("account_id", accountId);

				// 调用业务层
				accountService.UpdateAccount(Set_Param, Where_Param);

				HttpSession session = request.getSession();
				session.setAttribute("phone", accountPhone);
				session.setAttribute("accountId", accountId);
				session.setAttribute("name", accountName);
				// session.setAttribute("accountPic", accountPic);

				// 显示个人中心的信息
				accountCenter(request, response);
			} else {
				// 获取文件真实名:Servlet 3.0不提供获取上传文件名的方法,通过请求头信息间接获取
				String header = part.getHeader("content-disposition");
				String realName = header.substring(header.indexOf("filename=") + 10, header.length() - 1);
				// 获取真实文件名的后缀
				String fileSuffix = realName.substring(realName.lastIndexOf("."));
				// 使用时间戳+随机数自动生成文件名,避免文件名重复问题
				// JDK1.8 日期时间类
				LocalDateTime now = LocalDateTime.now();
				DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern("yyyyMMddhhmmssSSS");
				// 将当前日期时间转成字符串
				String formatDate = ofPattern.format(now);
				// 随机数
				int random = (int) (Math.random() * 1000 + 1);
				// 拼接
				StringBuffer fileName = new StringBuffer();
				fileName.append(formatDate).append(random);

				// 将文件存储在指定服务器中(本地电脑D盘)
				File file = new File("D:\\fileupload\\images");
				// 目录如果不存在，则创建
				if (!file.exists()) {
					file.mkdirs();
				} else {
					// 将文件写入指定位置
					String filePath = file.getPath() + File.separator + fileName + fileSuffix;
					part.write(filePath);
					DBUtil_Pro.abscut(filePath, x, y, destWidth, destHeight, finalWidth, finalHeight);
				}

				// 创建集合
				Map<String, Object> Set_Param = new HashMap<String, Object>();
				Set_Param.put("account_name", accountName);
				Set_Param.put("account_phone", accountPhone);
				Set_Param.put("account_email", accountEmail);
				Set_Param.put("account_pic", fileName + fileSuffix);

				Map<String, Object> Where_Param = new HashMap<String, Object>();
				Where_Param.put("account_id", accountId);

				// 调用业务层
				accountService.UpdateAccount(Set_Param, Where_Param);

				HttpSession session = request.getSession();
				session.setAttribute("phone", accountPhone);
				session.setAttribute("accountId", accountId);
				session.setAttribute("name", accountName);
				session.setAttribute("accountPic", fileName + fileSuffix);
				// 显示个人中心的信息
				accountCenter(request, response);
			}
		} else {
			// 进行MD5加密
			String newAccountPsw = DBUtil_Pro.getMd5(accountPsw);

			// 接受文件组件
			Part part = request.getPart("facePicture");

			// 允许的文件图片类型
			String allowImgType = "image/jpg,image/jpeg,image/png";
			// 允许的文件图片类型集合
			List<String> allowImgTypeList = Arrays.asList(allowImgType.split(","));

			// 判断上传的文件类型是否合法
			String contentType = part.getContentType(); // 获取上传文件的MIME类型
			if (allowImgTypeList.contains(contentType) == false) {

				// 创建集合
				Map<String, Object> Set_Param = new HashMap<String, Object>();
				Set_Param.put("account_name", accountName);
				Set_Param.put("account_phone", accountPhone);
				Set_Param.put("account_email", accountEmail);
				Set_Param.put("account_psw", newAccountPsw);

				Map<String, Object> Where_Param = new HashMap<String, Object>();
				Where_Param.put("account_id", accountId);

				// 调用业务层
				accountService.UpdateAccount(Set_Param, Where_Param);

				HttpSession session = request.getSession();
				session.setAttribute("phone", accountPhone);
				session.setAttribute("accountId", accountId);
				session.setAttribute("name", accountName);
				// 显示个人中心的信息
				accountCenter(request, response);
			} else {
				// 获取文件真实名:Servlet 3.0不提供获取上传文件名的方法,通过请求头信息间接获取
				String header = part.getHeader("content-disposition");
				String realName = header.substring(header.indexOf("filename=") + 10, header.length() - 1);
				// 获取真实文件名的后缀
				String fileSuffix = realName.substring(realName.lastIndexOf("."));
				// 使用时间戳+随机数自动生成文件名,避免文件名重复问题
				// JDK1.8 日期时间类
				LocalDateTime now = LocalDateTime.now();
				DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern("yyyyMMddhhmmssSSS");
				// 将当前日期时间转成字符串
				String formatDate = ofPattern.format(now);
				// 随机数
				int random = (int) (Math.random() * 1000 + 1);
				// 拼接
				StringBuffer fileName = new StringBuffer();
				fileName.append(formatDate).append(random);

				// 将文件存储在指定服务器中(本地电脑D盘)
				File file = new File("D:\\fileupload\\images");
				// 目录如果不存在，则创建
				if (!file.exists()) {
					file.mkdirs();
				} else {
					// 将文件写入指定位置
					String filePath = file.getPath() + File.separator + fileName + fileSuffix;
					part.write(filePath);
					
						DBUtil_Pro.abscut(filePath, x, y, destWidth, destHeight, finalWidth, finalHeight);
					

				}
				// 创建集合
				Map<String, Object> Set_Param = new HashMap<String, Object>();
				Set_Param.put("account_name", accountName);
				Set_Param.put("account_phone", accountPhone);
				Set_Param.put("account_email", accountEmail);
				Set_Param.put("account_psw", newAccountPsw);
				Set_Param.put("account_pic", fileName + fileSuffix);

				Map<String, Object> Where_Param = new HashMap<String, Object>();
				Where_Param.put("account_id", accountId);

				// 调用业务层
				accountService.UpdateAccount(Set_Param, Where_Param);

				HttpSession session = request.getSession();
				session.setAttribute("phone", accountPhone);
				session.setAttribute("accountId", accountId);
				session.setAttribute("name", accountName);
				session.setAttribute("accountPic", fileName + fileSuffix);
				// 显示个人中心的信息
				accountCenter(request, response);

			}
		}

	}

	private void orderView(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 从request获取session
		HttpSession session = request.getSession();

		// 从session中获取手机号
		String accountPhone = (String) session.getAttribute("phone");

		// 调用业务层
		List<Order> order = orderService.getOrderView(accountPhone);

		if (order != null) {
			// 利用第三方工具
			Gson gson = new Gson();

			// java对象转化成json字符串
			String jsonString = gson.toJson(order);

			response.setContentType("application/json");
			response.getWriter().write(jsonString);
		}

	}

	private void accountCenter(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 从request获取session
		HttpSession session = request.getSession();

		// 从session中获取手机号
		String accountPhone = (String) session.getAttribute("phone");

		// 调用业务层
		PageInfo<Account> pageInfo = accountService.getAccount();

		// 遍历结果集集合
		List<Account> list = pageInfo.getData();
		for (Account account : list) {
			if (account.getAccount_phone().equals(accountPhone)) {

				// 利用第三方工具
				Gson gson = new Gson();

				// java对象转化成json字符串
				String jsonString = gson.toJson(account);

				response.setContentType("application/json");
				response.getWriter().write(jsonString);
			}
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 获取op属性值（前端jsp页面、ajax异步请求传进来的值）
		String op = request.getParameter("op");

		// 进行判断
		if ("viewUpdate".equals(op)) {
			// 修改账户信息
			viewUpdate(request, response);

		}
	}

}
